home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!news
- From: giuliano@ix.netcom.com(Giuliano Carlini)
- Newsgroups: comp.lang.c++
- Subject: Re: How do I put DIFFERENT classes in the same linked list?
- Date: 8 Apr 1996 08:55:55 GMT
- Organization: Netcom
- Message-ID: <4kakar$i22@dfw-ixnews1.ix.netcom.com>
- References: <4ka938$bj6@wintermute.ecs.fullerton.edu>
- NNTP-Posting-Host: lbx-ca6-22.ix.netcom.com
- X-NETCOM-Date: Mon Apr 08 3:55:55 AM CDT 1996
-
- In <4ka938$bj6@wintermute.ecs.fullerton.edu> grosin@titan (Gil Rosin)
- writes:
- >
- >Here is the source code I have worked up so far:
- >
- >#include <iostream.h>
- >
- >class A
- > {
- > public:
- > A *next;
- > A *prev;
- > void Print();
- > };
- >
- >class Demo
- > {
- > public:
- > void Insert(A *Temp);
- > void Insert2(A *Temp);
- > void Test(void);
- > A *First;
- > };
- >
- >class B : public A
- > {
- > void Print();
- > };
- >
- >class C : public A
- > {
- > void Print();
- > };
- >
- >main()
- > {
- > Demo *T = new Demo;
- > A *Test = new B;
- > T->Insert(Test);
- > Test = new C;
- > T->Insert2(Test);
- > T->Test();
- > return 0;
- > }
- >
- >void B::Print()
- > {
- > cout << "I am in class B" << '\n';
- > }
- >
- >void C::Print()
- > {
- > cout << "I am in class C" << '\n';
- > }
- >
- >void Demo::Insert(A *Temp)
- > {
- > First = Temp;
- > }
- >
- >void Demo::Insert2(A *Temp)
- > {
- > First->next = Temp;
- > }
- >
- >void Demo::Test(void)
- > {
- > First->Print();
- > First->next->Print();
- > }
- >
- >void A::Print()
- > {
- > cout << "I am in class A" << '\n';
- > }
- >
-
- Make Print() virtual:
- virtual void Print();
-
- If you don't say "virtual" in the declaration, then C++ uses the static
- type - that is the type you declare for the variable - to select the
- function to call. Since Demo::First and A::Next are declared to be A*,
- the compiler selects A::Print no matter what the actual type is.
- Declaring Print to be virtual changes all that. Virtual tells the
- compiler to use the actual type when selecting the Print function to
- use.
-
- giuliano
-